<template>
	<view>
		<u-popup v-model="show" mode="bottom" borderRadius="20">
			<view class="fs32 fw-w tc pt30">{{title}}</view>
			<scroll-view class="h600 w-max p30">
				<checkbox-group @change="change">
					<u-empty marginTop="100" v-if="!selectList.length"></u-empty>
					<label class="pt20 pb20 border-b flex" v-for="(item,index) in selectList" :key="index">
						<view class="flex1">{{item.label}}</view>
						<view class="ml20">
							<checkbox :checked="item.checked" :value="item.value" :color="$zs" />
						</view>
					</label>
				</checkbox-group>
			</scroll-view>
			<view class="flex">
				<view class="flex1 p30">
					<u-button type="warning" plain ripple @click="getResult('cancel')">取消</u-button>
				</view>
				<view class="flex1 p30">
					<u-button type="warning" ripple @click="getResult('confirm')">确认</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	/**
	 * select-list 多选列表
	 * @property {Array} list 列数据，数组形式，见官网说明
	 * @property {String} default-value 提供的默认选中的下标，见官网说明
	 * @property {String} value-name 自定义list数据的value属性名 1.3.6
	 * @property {String} label-name 自定义list数据的label属性名 1.3.6
	 * @event {Function} confirm 点击确定按钮，返回当前选择的值
	 * @example <auto-select ref="list" :list="list" />
	 */
	export default {
		name: "select-list",
		props: {
			list: {
				default: ''
			},
			title: {
				type: String,
				default: '请选择'
			},
			// 自定义value属性名
			valueName: {
				type: String,
				default: 'value'
			},
			// 自定义label属性名
			labelName: {
				type: String,
				default: 'label'
			},
			checked: {
				type: [String, Array],
				default: ''
			},
			api: {
				default: ''
			},
			apiParams: {
				default: ''
			},
		},
		data() {
			return {
				show: false,
				selectList: [],
				selectValue: []
			};
		},
		methods: {
			async open(data = '') {
				let checked = this.checked
				if (typeof checked === 'string') {
					checked = checked && this.checked.split(',') || []
				}
				console.log(checked);
				if (this.selectList.length) {
					data = this.selectList
				} else if (data) {
					// this.selectList = data
				} else if (this.list) {
					this.selectList = this.list
				} else if (this.api) {
					let res = await this.$request(this.api, this.apiParams)
					data = res.data
				}
				this.selectList = data.map(e => {
					let obj = {
						...e,
						label: e[this.labelName],
						value: e[this.valueName] + '',
					}
					obj.checked = checked.includes(obj.value)
					return obj
				})
				this.show = true
			},
			getResult(event = null) {
				console.log(this.selectValue);
				if (event) this.$emit(event, this.selectValue);
				this.show = false
			},
			change(e) {
				this.selectValue = e.detail.value
				this.$emit('change', e.detail.value)
			}
		}
	}
</script>

<style lang="scss">

</style>